<template>
  <el-dialog
    :title="dialogTitle"
    :model-value="modelValue"
    @update:model-value="$emit('update:modelValue', $event)"
    width="70%"
    destroy-on-close
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
    >
      <el-form-item label="标题" prop="title">
        <el-input 
          v-model="form.title" 
          placeholder="请输入文章标题"
          maxlength="100"
          show-word-limit
        />
      </el-form-item>

      <el-form-item label="内容" prop="content">
        <div style="border: 1px solid #ccc; z-index: 9999">
          <Toolbar
            style="border-bottom: 1px solid #ccc"
            :editor="editorRef"
            :defaultConfig="toolbarConfig"
            :mode="mode"
          />
          <Editor
            style="height: 400px; overflow-y: hidden;"
            v-model="form.content"
            :defaultConfig="editorConfig"
            :mode="mode"
            @onCreated="handleCreated"
          />
        </div>
      </el-form-item>



      <el-form-item label="分类">
        <div class="categories-container">
          <el-tag
            v-for="category in form.categories"
            :key="category"
            :closable="true"
            :disable-transitions="false"
            class="category-item"
            :effect="category.hot ? 'dark' : 'plain'"
            @close="handleRemoveCategory(category)"
          >
            {{ category }}
            <el-badge v-if="category.hot" value="hot" class="category-badge" />
          </el-tag>
        </div>

        <div class="category-input-container">
          <el-select
            v-if="!inputVisible"
            v-model="selectedCategory"
            filterable
            allow-create
            default-first-option
            placeholder="请选择分类"
            @change="handleCategorySelect"
            :loading="categoriesLoading"
          >
            <el-option
              v-for="category in availableCategories"
              :key="category"
              :label="category"
              :value="category"
            >
              <span>{{ category }}</span>
              <span v-if="category.count" class="category-count">({{ category.count }})</span>
            </el-option>
          </el-select>
        </div>

      </el-form-item>



      <el-divider content-position="left">发布选项</el-divider>

      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="form.status">
          <el-radio-button label="draft">草稿</el-radio-button>
          <el-radio-button label="pending">审核中</el-radio-button>
          <el-radio-button label="published">发布</el-radio-button>
        </el-radio-group>
      </el-form-item>

      



      <el-divider content-position="left">封面图片</el-divider>

      <el-form-item label="封面图">
        <el-upload
          class="cover-uploader"
          action="/api/upload"
          :show-file-list="false"
          accept="image/*"
          :before-upload="beforeUpload"
          :on-success="handleUploadSuccess"
        >
          <div v-if="form.coverImage" class="cover-preview">
            <img :src="form.coverImage" class="cover-image" />
            <div class="cover-actions">
              <el-button type="primary" link>
                <el-icon><Edit /></el-icon>
                更换
              </el-button>
              <el-button type="danger" link @click.stop="removeCover">
                <el-icon><Delete /></el-icon>
                删除
              </el-button>
            </div>
          </div>
          <div v-else class="upload-placeholder">
            <el-icon class="cover-uploader-icon"><Plus /></el-icon>
            <span>点击上传封面图</span>
          </div>
        </el-upload>
        <div class="upload-tip">
          <el-alert
            type="info"
            :closable="false"
            show-icon
          >
            <template #title>
              建议上传 1200x675px 的图片
            </template>
            支持 jpg、png 格式，文件大小不超过 2MB
          </el-alert>
        </div>
      </el-form-item>


    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="loading">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch, onMounted, onBeforeUnmount } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Edit, Delete } from '@element-plus/icons-vue'
import { createArticle, updateArticle } from '@/views/api/article'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import '@wangeditor/editor/dist/css/style.css'

const props = defineProps({
  modelValue: {
    type: Boolean,
    required: true
  },
  article: {
    type: Object,
    default: null
  }
})

const emit = defineEmits(['update:modelValue', 'success'])

// 表单相关
const formRef = ref(null)
const loading = ref(false)

// 编辑器相关
const editorRef = ref()
const mode = ref('default')
const toolbarConfig = ref({})
const editorConfig = ref({
  placeholder: '请输入文章内容...',
  MENU_CONF: {
    uploadImage: {
      // 自定义图片上传配置
      server: '/api/upload', // 上传图片的服务器地址
      fieldName: 'file',
      maxFileSize: 2 * 1024 * 1024, // 2MB
      allowedFileTypes: ['image/*'],
      // 自定义插入图片
      customInsert(res, insertFn) {
        // 从后端返回的响应中获取图片URL
        if (res.url) {
          insertFn(res.url, 'image', res.url)
        }
      }
    }
  }
})

const form = ref({
  title: '',
  content: '',
  categories: [],
  status: 'draft',
  coverImage: '',
  readTime: 0
})

// 编辑器创建回调
const handleCreated = (editor) => {
  console.log('editor is created', editor)
  editorRef.value = editor // 记录 editor 实例，重要！
}

// 组件销毁前清除编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy() // 组件销毁时，及时销毁编辑器
})

// 表单验证规则
const rules = {
  title: [
    { required: true, message: '请输入文章标题', trigger: 'blur' },
    { min: 2, max: 100, message: '标题长度应在 2 到 100 个字符之间', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入文章内容', trigger: 'blur' },
    { min: 10, message: '内容不能少于 10 个字符', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择文章状态', trigger: 'change' }
  ],
  categories: [
    { required: true, message: '请至少选择一个分类', trigger: 'change' }
  ]
}

// 计算属性
const dialogTitle = computed(() => props.article ? '编辑文章' : '新增文章')

// 分类相关
const inputVisible = ref(false)
const selectedCategory = ref('')
const availableCategories = ref([])
const categoriesLoading = ref(false)

// 加载分类列表
const loadCategories = async () => {
  try {
    categoriesLoading.value = true
    // 使用预定义的分类列表替代 fetchCategories API 调用
    availableCategories.value = [
      '旅游攻略',
      '景点介绍',
      '美食推荐',
      '住宿指南',
      '交通指南',
      '购物指南'
    ]
  } catch (error) {
    console.error('Error loading categories:', error)
  } finally {
    categoriesLoading.value = false
  }
}

// 在组件挂载时加载分类
onMounted(() => {
  loadCategories()
})

// 监听文章数据变化
watch(
  () => props.article,
  (article) => {
    if (article) {
      // 确保categories是数组格式
      const categories = Array.isArray(article.categories) 
        ? article.categories 
        : typeof article.categories === 'string' 
          ? [article.categories] 
          : []
      
      form.value = {
        title: article.title || '',
        content: article.content || '',
        categories: categories,
        status: article.status || 'draft',
        coverImage: article.coverImage || '',
        readTime: article.readTime || 0
      }
    } else {
      form.value = {
        title: '',
        content: '',
        categories: [],
        status: 'draft',
        coverImage: '',
        readTime: 0
      }
    }
  },
  { immediate: true }
)

// 分类处理方法
const handleCategorySelect = (value) => {
  if (value && !form.value.categories.includes(value)) {
    form.value.categories.push(value)
  }
  selectedCategory.value = ''
}

const handleRemoveCategory = (category) => {
  form.value.categories = form.value.categories.filter(c => c !== category)
}

// 封面图上传
const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

const handleUploadSuccess = (response) => {
  form.value.coverImage = response.url
  ElMessage.success('封面图上传成功')
}

const removeCover = async (event) => {
  event.preventDefault()
  try {
    await ElMessageBox.confirm('确定要删除封面图吗？', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    form.value.coverImage = ''
    ElMessage.success('封面图已删除')
  } catch (error) {
    // 用户取消删除
  }
}

// 表单提交方法
const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    loading.value = true

    // 确保状态是有效的值
    const validStatuses = ['draft', 'pending', 'published'];
    if (!validStatuses.includes(form.value.status)) {
      form.value.status = 'draft'; // 默认设为草稿状态
    }

    // 如果文章状态为published，自动设置发布时间为当前时间
    let data = { ...form.value, authorId: 1 };
    if (form.value.status === 'published') {
      data.publishTime = new Date().toISOString().slice(0, 19).replace('T', ' ');
    } else {
      // 如果不是published状态，不发送publishTime字段
      delete data.publishTime;
    }
    if (props.article?.articleId) {
      await updateArticle(props.article.articleId, data)
      ElMessage.success('文章更新成功')
    } else {
      await createArticle(data)
      ElMessage.success('文章创建成功')
    }

    emit('success')
  } catch (error) {
    console.log('Error submitting article, full error:', error)
    if (error.response && error.response.data && error.response.data.message) {
      ElMessage.error(error.response.data.message)
    } else if (error.message) {
      ElMessage.error(error.message)
    } else {
      ElMessage.error('提交文章失败')
    }
    console.error('Error submitting article:', error)
    // 打印详细的错误信息
    if (error.response) {
      console.error('Error response:', error.response)
    }
  } finally {
    loading.value = false
  }
}



const handleCancel = () => {
  formRef.value?.resetFields()
  emit('update:modelValue', false)
}
</script>

<style scoped>
.categories-container {
  margin-bottom: 10px; /* 增加底部间距 */
  display: flex;
  flex-wrap: wrap;
  gap: 2px; /* 标签之间的间距 */
  align-items: flex-start; /* 顶部对齐 */
}

.category-item {
  transition: all 0.3s;
  position: relative;
  margin: 2px; /* 标签的外边距 */
  padding: 14px 8px; /* 增加标签内边距 */
  font-size: 14px; /* 增加标签字体大小 */
  line-height: 1.4; /* 设置行高 */

  &:hover {
    transform: translateY(-2px);
  }

  .category-badge {
    position: absolute;
    top: -8px;
    right: -8px;
    transform: scale(0.8);
  }
}

.category-input-container {
  display: flex;
  align-items: flex-start; /* 顶部对齐 */
  gap: 10px; /* 选择框和按钮之间的间距 */
  margin-top: 0px; /* 移除顶部间距 */

  .el-select {
    width: 260px; /* 选择框宽度 */
    align-self: flex-start; /* 选择框顶部对齐 */
  }

  .button-new-category {
    display: inline-flex;
    align-items: center;
    gap: 4px;
    height: 40px;
    padding: 0 12px;
    align-self: flex-start; /* 按钮顶部对齐 */
  }
}

.category-count {
  margin-left: 8px;
  color: var(--el-text-color-secondary);
  font-size: 12px;
}

.cover-uploader {
  border: 2px dashed var(--el-border-color);
  border-radius: 8px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 360px;
  height: 203px;
  transition: all 0.3s;

  &:hover {
    border-color: var(--el-color-primary);
    transform: translateY(-2px);
  }
}

.cover-preview {
  position: relative;
  width: 100%;
  height: 100%;

  &:hover .cover-actions {
    opacity: 1;
  }
}

.cover-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: filter 0.3s;

  &:hover {
    filter: brightness(0.8);
  }
}

.cover-actions {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 12px;
  background: linear-gradient(transparent, rgba(0, 0, 0, 0.6));
  display: flex;
  justify-content: center;
  gap: 16px;
  opacity: 0;
  transition: opacity 0.3s;

  .el-button {
    color: white;

    &:hover {
      color: var(--el-color-primary);
    }
  }
}

.upload-placeholder {
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: var(--el-text-color-secondary);

  .cover-uploader-icon {
    font-size: 32px;
    margin-bottom: 8px;
  }
}

.upload-tip {
  margin-top: 12px;
  width: 360px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding-top: 16px;
}

:deep(.el-upload) {
  width: 100%;
  height: 100%;
}

:deep(.el-form-item__content) {
  flex-wrap: wrap;
}

:deep(.el-alert) {
  margin: 0;
}

:deep(.el-divider__text) {
  font-size: 14px;
  color: var(--el-text-color-secondary);
}

:deep(.el-form-item) {
  margin-bottom: 24px;
}
</style>